﻿using _17Net8AspNetCore_JWT.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace _17Net8AspNetCore_JWT.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        [HttpPost]
        public IActionResult createToken(User user)
        {
            // 登录判断
            if (true)
            {
                //2、创建jwt声明集合
                var claimUsers = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Name, user.Name),
                    new Claim(JwtRegisteredClaimNames.UniqueName, user.PassWord),
                    // JWT唯一标识符，防止重放攻击
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                };

                // 3\创建JWT Json
                // 3.1、SigningCredentials 初始化
                // 3.1.1\ SecurityKey 初始化
                // 秘钥：ThisIsASecretKeyForJwtTokenWithSufficientLength
                SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("ThisIsASecretKeyForJwtTokenWithSufficientLength"));
                // 3.1.2\加密算法准备 [对称算法]

                SigningCredentials signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
                JwtSecurityToken token = new JwtSecurityToken(
                    issuer:"JWT",
                    audience:"17_NET8",
                    claims: claimUsers,
                    notBefore: DateTime.Now,
                    expires:DateTime.Now.AddMinutes(10),
                    signingCredentials: signingCredentials);

                // 4、创建Token
                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                string tokenString = handler.WriteToken(token);

                // 5\返回Token
                return Ok(tokenString);
            }
            return Ok("无Token");
        }
    }
}
